﻿using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Http;
using System.Web;
using UtilsORM;
using UtilsORM.MySqlData;
using Models.Common;
using UtilsORM.MySqlData;
using UtilsBase;
using UtilsCache;
using System.Security.Claims;

namespace FileServer.Common
{
    public class BaseMagerController : Controller
    {
        //
        // GET: /Base/
        protected MagerLoginInfo LoginUserInfo = new MagerLoginInfo();

        ////复写父类的该方法。执行控制器中的方法之前先执行该方法。从而实现过滤的功能。
        //public override void OnActionExecuting(ActionExecutingContext filterContext)
        //{
        //    //string _controllerName = filterContext.RouteData.Values["controller"].ToString();
        //    //string _actionName = filterContext.RouteData.Values["action"].ToString();
        //    //object _routeName = filterContext.RouteData.DataTokens["area"];
        //    base.OnActionExecuting(filterContext);  //调用父类的该方法。
        //    if (Request.Cookies["CurrentUser"].ToString() != null)
        //    {
        //        //filterContext.HttpContext.Response.Redirect("/QRCodeRecruitment/Index");  //这种跳转方式，会继续向下执行Controller的方法并返回IActionResult。
        //    }
        //    else
        //    {
        //        //这种跳转方式直接返回一个IActionResult，不会继续向下执行，而是直接跳转。速度快。
        //        filterContext.Result = Redirect("/Login/index"); ///ManageUATClient
        //    }
        //}
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            base.OnActionExecuting(filterContext);
            LoginUserInfo = BaseUserLoginInfo(filterContext);
            if (LoginUserInfo == null)
            {
                filterContext.Result = Redirect("/MagerLogin/LogOut");
                return;
            }
        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

        }

        public MagerLoginInfo BaseUserLoginInfo(ActionExecutingContext context)
        {


            //判断是否有cookie
            if (HttpContext.GetCookiesValue("LoginUserInfo") != null)
            {
                string logintoken = HttpUtility.UrlDecode(HttpContext.GetCookiesValue("LoginUserInfo").ToString());

                string token = logintoken.Split('|')[0];
                string GetTimeStamp = logintoken.Split('|')[2];
                DateTime gettime = UtilsDateTime.getStampToDateTime(long.Parse(GetTimeStamp));
                string checktoken = UtilsDecrypt.MD5Encrypt(LoginUserInfo.user_id + GetTimeStamp);
                if (token != checktoken || gettime < DateTime.Now.AddDays(-1))
                {//核查有效性

                    HttpContext.DeleteCookies("LoginUserInfo");
                }
                else
                {
                    LoginUserInfo.user_id = int.Parse(logintoken.Split('|')[1]);
                }
            }

            if (LoginUserInfo.user_id == 0)
            {
                var userId = "1";// User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value; ;
                LoginUserInfo.user_id = int.Parse(userId);
            }

            string sql = @"select * from  bs_client_user where cu_id=@cu_id  ";
            DataTable dt = new MySqlYihongFileServer().Db.Ado.GetDataTable(sql, new { cu_id = LoginUserInfo.user_id }); //DBUtility.MySqlHelper.GetDataTable(sql, spterempguid);
            if (dt.Rows.Count > 0)
            {
                LoginUserInfo.user_Name = dt.Rows[0]["cu_name"].ToString();
                LoginUserInfo.user_guid = dt.Rows[0]["cu_guid"].ToString();
            }
            dt.Dispose();


            if (HttpContext.GetCookiesValue("LoginUserInfo") == null)
            {
                //写入缓存或cookie
                string GetTimeStamp = UtilsDateTime.getTimeStamp().ToString();
                HttpContext.SetCookies("LoginUserInfo", HttpUtility.UrlEncode(UtilsDecrypt.MD5Encrypt(LoginUserInfo.user_id + GetTimeStamp) + "|" + LoginUserInfo.user_id + "|" + GetTimeStamp));



            }
            return LoginUserInfo;
        }

    }
}
